package com.app.ctzoverseas.page.main.home

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.aliyun.auikits.aiagent.ARTCAICallEngine
//import com.aliyun.auikits.aiagent.ARTCAICallEngine.ARTCAICallAgentType
import com.aliyun.auikits.aicall.AUIAIChatInChatActivity
import com.aliyun.auikits.aicall.base.SessionHistoryManager
import com.aliyun.auikits.aicall.util.AUIAICallAgentIdConfig
import com.aliyun.auikits.aicall.util.AUIAIConstStrKey
import com.aliyun.auikits.aicall.util.SettingStorage
import com.aliyun.auikits.aicall.util.SharedPreferencesUtils
import com.android.basemvvm.BaseVMFragment
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.cardetective.shopcar.R
import com.cardetective.shopcar.databinding.FragmentHomeBinding
import com.cardetective.shopcar.page.activity.main.AiCreateActivity
import com.permissionx.guolindev.PermissionX
import com.pinyuana.dragongame.adapter.HomeChatAdapter
import com.pinyuana.dragongame.utils.PermissionUtils
import kotlinx.coroutines.launch
import java.util.Collections



class HomeFragment : BaseVMFragment<HomeViewModel, FragmentHomeBinding>() {
    private var mLoginUserId: String? = null
    private var mLoginAuthorization: String? = null
    private val mHMDes = "嗨，我是你的新朋友秘和密！初次见面很开心。我呢，可以回答你的各种问题，给你工作学习上提供帮助，还能随时陪你聊天。嗯，你想问点什么呢？"

    private val chatAdapter by lazy { HomeChatAdapter() }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        mBinding?.let {
            mBinding?.rootPage?.setPadding(
                SizeUtils.dp2px(16f),
                BarUtils.getStatusBarHeight(),
                SizeUtils.dp2px(16f),
                0
            )
            setOnViewClick(
                it.ivAddChat
            )
            initListener()
        }
        SettingStorage.getInstance().init(activity)
    }

    private fun initListener() {
        val mhmLastMessage:String = SharedPreferencesUtils.getParam(activity, "m_h_m_userid", "").toString()
        mBinding?.tvMhmDes?.text = mhmLastMessage

        mBinding?.llMHM?.setOnClickListener {
            val useEmotional = SettingStorage.getInstance().getBoolean(
                SettingStorage.KEY_BOOT_ENABLE_EMOTION,
                SettingStorage.DEFAULT_BOOT_ENABLE_EMOTION
            )
            var agentId: String? = ""
            agentId = AUIAICallAgentIdConfig.getAIAgentId(
                ARTCAICallEngine.ARTCAICallAgentType.ChatBot, useEmotional
            )

            val keywordsList: ArrayList<String> = ArrayList(keywordsRamade.shuffled().take(5))
            jumpToInCallActivity("m_h_m_userid", agentId, "m_h_m_userid", "秘和密",mHMDes,keywordsList,"1","0")
        }

        mBinding?.rvSort?.layoutManager = LinearLayoutManager(activity)
        mBinding?.rvSort?.adapter = chatAdapter

        val sessionHistory = SessionHistoryManager.getSessionHistory(activity)
        Collections.reverse(sessionHistory);
        chatAdapter.setList(sessionHistory)
//        chatAdapter.setEmptyView(R.layout.layout_empty_list)

        chatAdapter.setOnItemClickListener { adapter, view, position ->
            val sessionHistory1 = chatAdapter.data[position]
            val sessionId = sessionHistory1.sessionId
            val agentId = sessionHistory1.agentId
            val userId = sessionHistory1.userId
            val nickname = sessionHistory1.nickName
            val aiDes = sessionHistory1.aiDes
            val aikeywordslist = sessionHistory1.aiKeywords
            val aiImgType = sessionHistory1.aiImgType

            jumpToInCallActivity(sessionId, agentId, userId, nickname,aiDes,aikeywordslist,aiImgType,"1")
        }

        PermissionX.init(this)
            .permissions(PermissionUtils.getPermissions())
            .request({ allGranted, grantedList, deniedList ->
                if (!allGranted) {
                    ToastUtils.showShort("请开通权限后重试")
//                    finish()
                } else {
//                    onAllPermissionGranted()
                }
            })
    }

    override fun onResume() {
        super.onResume()
        val mhmLastMessage:String = SharedPreferencesUtils.getParam(activity, "m_h_m_userid", "您还没有聊天呢，快去问问吧！").toString()
        mBinding?.tvMhmDes?.text = mhmLastMessage

        val sessionHistory = SessionHistoryManager.getSessionHistory(activity)
        LogUtils.e("jihe", sessionHistory)
        Collections.reverse(sessionHistory);
        chatAdapter.setList(sessionHistory)
    }

    override fun onClickSlow(view: View?) {
        super.onClickSlow(view)
        when (view) {
            mBinding?.ivAddChat -> {
                val intent = Intent(activity, AiCreateActivity().javaClass)
                startActivity(intent)

//                mLoginUserId = "user_${java.util.UUID.randomUUID().toString().substring(0, 8)}"  // 生成8位随机用户ID
//                mLoginAuthorization = "mock_authorization"
//
//                val useEmotional = SettingStorage.getInstance().getBoolean(
//                    SettingStorage.KEY_BOOT_ENABLE_EMOTION,
//                    SettingStorage.DEFAULT_BOOT_ENABLE_EMOTION
//                )
//
//                var agentId: String? = ""
//                agentId = AUIAICallAgentIdConfig.getAIAgentId(
//                    ARTCAICallEngine.ARTCAICallAgentType.ChatBot, useEmotional
//                )
//                val sessionId = mLoginUserId + "_" + agentId;
////                createSessionHistory(sessionId,mLoginUserId?:"",agentId,"你还没有提问")
//                jumpToInCallActivity(sessionId, agentId, mLoginUserId ?: "",(1..10).random().toString())
            }
        }
    }

    override fun initObserve() {
        super.initObserve()
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.CREATED) {
                launch {
                }
            }
        }
    }

    private fun jumpToInCallActivity(
        sessionId: String,
        agentId: String,
        userId: String,
        nickname: String,
        aiDes: String,
        aikeywordslist: ArrayList<String>,
        aiImgType: String,
        aiType:String
    ) {
        val intent = Intent(activity, AUIAIChatInChatActivity::class.java)
        intent.putExtra(AUIAIConstStrKey.BUNDLE_KEY_LOGIN_USER_ID, userId)
        intent.putExtra(AUIAIConstStrKey.BUNDLE_KEY_LOGIN_AUTHORIZATION, mLoginAuthorization)
        intent.putExtra(
            AUIAIConstStrKey.BUNDLE_KEY_AI_AGENT_TYPE,
            ARTCAICallEngine.ARTCAICallAgentType.ChatBot
        )
        intent.putExtra(AUIAIConstStrKey.BUNDLE_KEY_AI_AGENT_ID, agentId)
        intent.putExtra(AUIAIConstStrKey.BUNDLE_KEY_IS_SHARED_AGENT, false)
        intent.putExtra(AUIAIConstStrKey.BUNDLE_KEY_SESSION_ID, sessionId)
        intent.putExtra(AUIAIConstStrKey.BUNDLE_KEY_NICKNAME, nickname)
        intent.putExtra(AUIAIConstStrKey.BUNDLE_KEY_AI_DES, aiDes)
        intent.putExtra(AUIAIConstStrKey.BUNDLE_KEY_AI_KEYWORDS, aikeywordslist)
        intent.putExtra(AUIAIConstStrKey.BUNDLE_KEY_IMG_TYPE, aiImgType)
        intent.putExtra(AUIAIConstStrKey.BUNDLE_KEY_AI_TYPE, aiType)
        startActivity(intent)
    }

    // 关键词随机
    private val keywordsRamade = listOf(
        "下一个爆款行业是什么？",
        "只有2000，可以买个什么性价比高的手机？",
        "想学习英语，没有基础怎么办？",
        "电动车买什么牌子比较好？",
        "如何用AI提升工作效率？",
        "健康减脂的饮食方案推荐",
        "ChatGPT有哪些创新用法？",
        "零基础如何做短视频赚钱？",
        "新能源汽车值得现在入手吗？",
        "Python入门最快的学习路径",
        "元宇宙目前有哪些实际应用？",
        "家庭智能家居如何配置？",
        "大学生毕业如何选择城市？",
        "个人隐私如何防止AI泄露？",
        "区块链技术现在能做什么？",
        "如何应对中年职业危机？",
        "跨境电商还能做吗？",
        "儿童教育怎样平衡兴趣与学业？",
        "智能手环的健康数据准确吗？",
        "碳中和会给普通人带来什么机会？",
        "GPT-4相比3.5有哪些提升？",
        "家庭装修如何避免智商税？",
        "自由职业者怎么缴纳社保？",
        "2024年最值得投资的领域？",
        "如何辨别网络谣言？",
        "露营装备该怎么挑选？",
        "年轻人该不该提前还房贷？",
        "电子书和纸质书哪个更好？",
        "如何培养孩子的编程兴趣？",
        "家用投影仪怎么选不踩坑？"
    )

}